//
//  XGAccountViewModel.m
//  Instagram
//
//  Created by monkey on 2019/4/13.
//  Copyright © 2019 itcast. All rights reserved.
//

#import "XGAccountViewModel.h"

/// 错误信息key
static NSString *kLeanCloudErrorKey = @"com.leancloud.restapi.response.error";

/// 邮箱已经被注册
static NSInteger const kUserEmailHasBeenRegistered = 203;
/// 密码错误
static NSInteger const kUserNamePasswordMismatch = 210;
/// 用户名不存在
static NSInteger const kUserNameNotFound = 211;
/// 用户信息未验证
static NSInteger const kUserEmailNotVerified = 216;

NSString* errorMessageWithCode(NSInteger code);

@implementation XGAccountViewModel

#pragma mark - 子类化配置

/// 昵称
@dynamic screenName;
/// 性别
@dynamic gender;
/// 描述信息
@dynamic descriptionInfo;
/// 头像
@dynamic userIcon;

+ (void)load
{
    [XGAccountViewModel registerSubclass];
}

+ (NSString *)parseClassName
{
    return @"_User";
}

#pragma mark - 登录注册方法

+ (void)loginWithEmail:(NSString *)email password:(NSString *)password completion:(void (^)(BOOL, NSString * _Nonnull))completion
{
    // 处理登录
    [self logInWithUsernameInBackground:email password:password block:^(AVUser *user, NSError *error) {
        if (user != nil) {
            completion(YES,@"登录成功");
            return;
        } else {
            NSInteger code = [error.userInfo[kLeanCloudErrorKey][@"code"] integerValue];
            completion(NO,errorMessageWithCode(code));
            return;
        }
    }];
}

+ (void)registerAccountWithEmail:(NSString *)email password:(NSString *)password screenName:(NSString *)screenName gender:(XGGenderType)gender descriptionInfo:(NSString *)descriptionInfo userIcon:(UIImage *)userIcon completion:(void (^)(BOOL isSuccess,NSString *message))completion
{
    XGAccountViewModel *account = [XGAccountViewModel object];
    account.email = email;// 设置邮箱
    account.username = email;// 设置用户名
    account.password = password;// 设置密码
    account.screenName = screenName; // 设置昵称
    account.descriptionInfo = descriptionInfo; // 设置个人描述
    account.gender = gender; // 设置性别 0 男 1 女
    account.userIcon = [AVFile fileWithData: UIImageJPEGRepresentation(userIcon, 1) name:@"icon.jpg"]; // 设置头像 图片清晰度 0~1
    [account signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            // 注册成功
            completion(YES,@"注册成功,请前往邮箱进行验证后登录");
            return;
        } else {
            // 失败的原因可能有多种，常见的是用户名已经存在。
            NSInteger code = [error.userInfo[kLeanCloudErrorKey][@"code"] integerValue];
            completion(NO,errorMessageWithCode(code));
            return;
        }
    }];
}

+ (void)resetPasswordWithEmail:(NSString *)email completion:(void (^)(BOOL, NSString * _Nonnull))completion
{
    [self requestPasswordResetForEmailInBackground:email block:^(BOOL succeeded, NSError * _Nullable error) {
        if (succeeded) {
            completion(YES,@"重置请求成功,请前往邮箱进行密码重置");
            return;
        } else {
            NSInteger code = [error.userInfo[kLeanCloudErrorKey][@"code"] integerValue];
            completion(NO,errorMessageWithCode(code));
            return;
        }
    }];
}

- (void)updatePasswordWithOriginal:(NSString *)originalPassword newPassword:(NSString *)newPassword completion:(void (^)(BOOL, NSString * _Nonnull))completion
{
    [self updatePassword:originalPassword newPassword:newPassword block:^(AVUser*  _Nullable user, NSError * _Nullable error) {
        if (error == nil) {
            // 更新成功
            completion(YES,@"密码修改成功!");
            return;
        }
        
        NSInteger code = [error.userInfo[kLeanCloudErrorKey][@"code"] integerValue];
        completion(NO,errorMessageWithCode(code));
    }];
}

- (void)updateEmail:(NSString *)email completion:(void (^)(BOOL, NSString * _Nonnull))completion
{
    self.email = email;
    [self saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        if (succeeded) {
            completion(YES,@"修改成功,请前往邮箱进行验证后登录");
            return;
        }
        
        NSInteger code = [error.userInfo[kLeanCloudErrorKey][@"code"] integerValue];
        completion(NO,errorMessageWithCode(code));
    }];
}

+ (void)verifyEmail:(NSString *)email completion:(void (^)(BOOL, NSString * _Nonnull))completion
{
    [self requestEmailVerify:email withBlock:^(BOOL succeeded, NSError * _Nullable error) {
        if (succeeded) {
            completion(YES,@"邮件发送成功,请前往邮箱进行认证");
            return;
        }
        
        NSInteger code = [error.userInfo[kLeanCloudErrorKey][@"code"] integerValue];
        completion(NO,errorMessageWithCode(code));
    }];
}

@end

/**
 c语言函数 根据错误码返回错误信息

 @param code 错误码
 @return 错误信息
 */
NSString* errorMessageWithCode(NSInteger code)
{
    NSString *message = nil;
    switch (code) {
        case kUserEmailHasBeenRegistered:
            message = @"此邮箱已经被注册";
            break;
        case kUserNamePasswordMismatch:
            message = @"密码错误";
            break;
        case kUserNameNotFound:
            message = @"用户名不存在!";
            break;
        case kUserEmailNotVerified:
            message = @"用户邮箱未验证";
            break;
        default:
            message = @"未知错误";
            break;
    }
    
    return message;
}
